package com.regis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.regis.comment.CodeMsg;
import com.regis.comment.GlobalException;
import com.regis.comment.uilts.ThreadDataUtil;
import com.regis.entity.db.*;
import com.regis.service.*;
import com.regis.mapper.OrdersMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
* @author 纱雾休比酱
* @description 针对表【orders(订单表)】的数据库操作Service实现
* @createDate 2022-07-28 03:58:08
*/
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
    implements OrdersService{

    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders Orders
     */
    @Transactional
    @Override
    public void submit(Orders orders) {
        //获取当前用户id
        long userId = ThreadDataUtil.getValue();

        //获取购物车数据
        List<ShoppingCart> shoppingCarts =
                shoppingCartService.list(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getUserId, userId));
        if(shoppingCarts.size()==0){
            throw new GlobalException(new CodeMsg("购物车为空！"));
        }

        //查询用户数据
        User user = userService.getById(userId);
        //订单号
        long orderId = IdWorker.getId();

        //查询地址数据
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        System.out.println(addressBook);
        if(Objects.isNull(addressBook)){
            throw new GlobalException(new CodeMsg("地址有误！"));
        }

//        BigDecimal amount = new BigDecimal(0);
        AtomicInteger amount = new AtomicInteger(0);//原子操作，保证线程安全

        //整理订单明细数据
        List<OrderDetail> orderDetailList = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item,orderDetail);
            orderDetail.setOrderId(orderId);
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //插入订单表
        orders.setId(orderId);
        orders.setNumber(Long.toString(orderId));//设置订单号
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
            + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
            + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
            + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        this.save(orders);

        //插入订单明细表
        orderDetailService.saveBatch(orderDetailList);

        //清空购物车
        shoppingCartService.remove(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getUserId, userId));
    }
}




